(function(window){
//实现js文件的缓存
var JC = {
    HEAD : "head" ,
    BODY : "body" ,
    VERSION : "2015061915324" ,
    KEYPREFIX : "2092_CF_WX_",
    //加载js文件
    load : function(filePath ,version ,tag ,params) {
        if (arguments.length == 2 && typeof(arguments[1]) == 'object') {
            params = arguments[1];
            version = null;
            tag = null;
        };
        tag = tag || JC.HEAD;
        version = version || JC.VERSION;
        var source = JC.getCacheJSData(filePath ,version);
		if(source.error>0){
			$(tag).append("<script src='"+filePath+"?v="+version+"'><\/script>");
			return false;
		}else{
			source=source.msg;
		}
        if(params) {
            source = source.replace('[%params%]',JSON.stringify(params));
        }
        var script = document.createElement("script");
        script.language = "javascript";
        script.type = "text/javascript";
        script.defer = false;
        script.text = source;
        var heads = document.getElementsByTagName(tag);
        if(heads.length) {
            heads[heads.length-1].appendChild(script);
        } else {
            document.documentElement.appendChild(script);
        }
		return true;
    } ,
    //请求js文件
    getCacheJSData : function(filePath ,version) {
        var source = null;
		var skey=base64_encode(filePath);
        if(version) { //获得版本号
            source = S(skey,"",version);
			//console.log(source);
			if(source){
				//console.log(filePath+"使用了缓存");
				return source;
			}
        }
		var data={
				//runThreadKey:url_token,
				url:filePath,
		};
		
		//if(filePath.indexOf("http")>-1){
//			var url = base_url+"/BoxApi/Index/getRes";
//			var dataType="json";
//		}else{
//			var url =	filePath;
//			var dataType="text";
//			data={};
//		}
		var url =	filePath;
		var dataType="text";
		data={};
        //如果没有缓存则网络请求js
        $.ajax({ //同步请求js文件
            async : false,
            cache : false ,
            dataType: dataType,
			data:data,
			url: url,
			success: function(data) {
				if(typeof(data)=="string"){
                	source = {error:0,msg:data};
				}else{
					 source = data;
				}
			}
		});
		//console.log(source);
        if(version){
			S(skey,source,version);
		}
        return source;
    }
};

window.JS = JC;
var CSS = {
    HEAD : "head" ,
    BODY : "body" ,
    VERSION : "2015061915324" ,
    KEYPREFIX : "2092_CF_WX_",
    //加载js文件
    load : function(filePath ,version ,tag ,params) {

        if (arguments.length == 2 && typeof(arguments[1]) == 'object') {
            params = arguments[1];
            version = null;
            tag = null;
        };

        tag = tag || JS.HEAD;
        version = version || JS.VERSION;
        var source = JS.getCacheJSData(filePath ,version);
       if(source.error>0){
			document.write('<link rel="stylesheet" href="'+filePath+'?v='+version+'" type="text/css">');
			return false;
		}
		source=source.msg;
        if(params) {
            source = source.replace('[%params%]',JSON.stringify(params));
        }

        var script = "<style>"+source+"</style>";
        $(tag).append(script);
		return true;
    }
};
window.CSS = CSS;		

var TPL = {
    HEAD : "body" ,
    BODY : "body" ,
    VERSION : "2015061915324" ,
    KEYPREFIX : "2092_CF_WX_",
    //加载js文件
    load : function(filePath ,version ,tag ,params) {
        if (arguments.length == 2 && typeof(arguments[1]) == 'object') {
            params = arguments[1];
            version = null;
            tag = null;
        };
        tag = tag || TPL.HEAD;
        version = version || JS.VERSION;
        var source = JS.getCacheJSData(filePath ,version);
		
       if(source.error>0){
			return false;
		}
		source=source.msg;
        if(params) {
            source = source.replace('[%params%]',JSON.stringify(params));
        }
		//console.log(tag);
        $(tag).append(source);
		return true;
    }
};
window.TPL = TPL;	

			
})(window);





//使用store.js 缓存 最大4M

function S(key,value,version){
	if(typeof(key)=="string" && key.indexOf('con-') === 0){ //不用加版本号的缓存
		key = key.slice(4);
	}else if(typeof(version)!="undefined"){
		key=version+":"+key;
	}else if( typeof(app_params) != "undefined" && app_params['cache_v']){
		key=app_params['cache_v']+":"+key;
	}
	if (!store.enabled) {
		return false;	
	}
	if(value===null){
		store.remove(key);
	}
	if(value){
		try {
			store.set(key, value);
		}catch(err) {
			if(err.name == 'QuotaExceededError') {
				store.clear(); //如果缓存已满则清空
			}
		}
	}
	if(typeof(value)=="undefined" || value==""){
		return store.get(key);
	}
	if(typeof(key)=="undefined"){
		return store.getAll();
	}
	if(key==null){
		store.clear()
	}
}

function F(key,value,expiry){
	if(app_params.view_type=="app"){
		return fs_save(key,value);
	}else{
			//return DB_Cache(key,value,expiry);
			return null;
	}
}



function Fget(key,f1,f2){
	if(app_params.view_type=="app"){
		fs_get(key,f1,f2);
	}else{
		 f2();
			//DB_Get_Cache(key,f1,f2);
		//return null;
	}
}
/****app 使用apicloud **/
function fs_save(key,value){
	PageVersionCache=PageVersionCache||1;
	var path='fs://page_cache/'+PageVersionCache+'/'+key+'.txt';
	if(key===null){
		_delete_dir("fs://page_cache");
		return ;
	}
	if(typeof(value)=="undefined" || value==""){
		return ;
	}
	if(typeof(value)=="string"){
		value="str-"+value;
	}
	if(typeof(value)=="object"){
		value="obj-"+JSON.stringify(value);
	}
	if(value===null){
		 _delete_file(path);
		 return ;
	}
	var fs = api.require('fs');//'fs://floder'
	fs.getAttribute({
		path: path
	}, function(ret, err){        
		if( ret.status ){
			//_read_file(path);
			_write_file(path,value);
		}else{
			fs.createFile({
				path: path
			}, function(ret, err){        
				if( ret.status ){
					_write_file(path,value);
				}else{
					//alert( "创建缓存文件失败:"+JSON.stringify( err ) );
				}
			});
		}
	});
}

function fs_get(key,f1,f2){
	PageVersionCache=PageVersionCache||1;
	var path='fs://page_cache/'+PageVersionCache+'/'+key+'.txt';
	_read_file(path,f1,f2);
}

/*****删除文件夹****/
function _delete_dir(path){
	var fs = api.require('fs');//'fs://floder'
	fs.remove({
    path: path
	}, function(ret, err){        
		if( ret.status ){
			//alert( JSON.stringify( ret ) );
		}else{
			//alert( JSON.stringify( err ) );
		}
	});
}

/*****删除文件****/
function _delete_file(path){
	var fs = api.require('fs');
	fs.remove({
    path: path
	}, function(ret, err){        
		if( ret.status ){
			//alert( JSON.stringify( ret ) );
		}else{
			//alert( JSON.stringify( err ) );
		}
	});
}
/*****写入文件****/
function _write_file(path,value){
	var fs = api.require('fs');
	fs.open({
			path: path,
			flags: 'read_write'
		}, function(ret, err){        
		if( ret.status ){
			var fd_id= ret.fd;
			 fs.write({
					fd: fd_id,
					data: value,
					offset: 0
				}, function(ret, err){        
					if( ret.status ){
						//alert( "写入成功了："+JSON.stringify( ret ) );
					}else{
						//alert( "写入页面缓存失败了:"+JSON.stringify( err ) );
					}
				});
				_colse_file(fd_id);
		}else{
			//alert( "打开失败了:"+JSON.stringify( err ) );
		}
	});
}


function _read_file(path,f1,f2){
	var fs = api.require('fs');
	fs.open({
			path: path,
			flags: 'read'
		}, function(ret, err){        
		if( ret.status ){
			var fd_id=ret.fd;
			fs.read({
				fd: fd_id,
			}, function(ret, err){        
				if( ret.status ){
					var data=ret.data;
					if(data.indexOf('str-') === 0){ 
						data = data.slice(4);
						//alert( "读成功了："+data );
					}
					if(data.indexOf('obj-') === 0){ 
						data = data.slice(4);
						data= JSON.parse(data);
						//alert( "读成功了："+JSON.stringify( data ) );
					}
					//alert( "页面使用了缓存");
					f1(data);
				
				}else{
					f2();
					//alert( "读取缓存失败了:"+JSON.stringify( err ) );
				}
				_colse_file(fd_id);
				
			});
		}else{
			f2();
			//alert( "打开缓存失败了:"+JSON.stringify( err ) );
		}
	});
}


function _colse_file(fd_id){
	var fs = api.require('fs');
	fs.close({
    	fd: fd_id
	});
}

/*******indexedDB实现缓存*****/
function DB_Get_Cache(key,f1,f2){
	var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; 
    if(!indexedDB) { 
					f2();
    } 
	if(key===null){
		$.indexedDB("myIndexedDB").objectStore("cache")["delete"];
		return ;	
	}
	$.indexedDB("myIndexedDB").objectStore("cache").get(key).then(function(item){
			if(typeof(item) == "undefined"){
				data=null;
			}else{
				var timestamp = (new Date()).valueOf();
				if(item.expiry < timestamp && item.expiry!=0){
					data=null;
				}else{
					data=item.value;
				}
			}
			if(data){
				console.log("使用了缓存");
				f1(data);
			}else{
				console.log(key+"：没有缓存");
				console.log(item);
				f2();
			}
		},function(err, e){
			console.log("没有get到数据");
			f2();
		}); 
}
/*******indexedDB实现缓存*****/
function DB_Cache(key,value,expiry){
	var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; 
    if(!indexedDB) { 
		return null;
    } 
	if(typeof(expiry)!="number"){
		expiry=0;	
		var timestamp=0;
	}else{
		var timestamp = (new Date()).valueOf()+expiry*1000;	
	}
	var item={
			key:key,
			value:value,
			expiry:timestamp,
	}
	
	 /***删除**/
	 if(value===null){
		 $.indexedDB("myIndexedDB").objectStore("cache")["delete"](key);
	 }	
	 /****设置保存**/
	 if(value){
		 $.indexedDB("myIndexedDB", {
            	"schema": {
					"2": function(versionTransaction){
            			var cache = versionTransaction.createObjectStore("cache", {
            				"autoIncrement": false,
							"keyPath": "key"
            			});
            			cache.createIndex("key");
            		}
            	}
            }).done(function(){
            	
     	});
		  $.indexedDB("myIndexedDB").objectStore("cache")["delete"](key).done(function(){
			  $.indexedDB("myIndexedDB").objectStore("cache").add(item);  		
		  });
	 }	
}

/*
         * Javascript base64_encode() base64加密函数
           用于生成字符串对应的base64加密字符串
         * 吴先成  www.51-n.com ohcc@163.com QQ:229256237
         * @param string str 原始字符串
         * @return string 加密后的base64字符串
        */
function base64_encode(str){
                var c1, c2, c3;
                var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";                
                var i = 0, len= str.length, string = '';

                while (i < len){
                        c1 = str.charCodeAt(i++) & 0xff;
                        if (i == len){
                                string += base64EncodeChars.charAt(c1 >> 2);
                                string += base64EncodeChars.charAt((c1 & 0x3) << 4);
                                string += "==";
                                break;
                        }
                        c2 = str.charCodeAt(i++);
                        if (i == len){
                                string += base64EncodeChars.charAt(c1 >> 2);
                                string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                                string += base64EncodeChars.charAt((c2 & 0xF) << 2);
                                string += "=";
                                break;
                        }
                        c3 = str.charCodeAt(i++);
                        string += base64EncodeChars.charAt(c1 >> 2);
                        string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                        string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
                        string += base64EncodeChars.charAt(c3 & 0x3F)
                }
                        return string
        }
		
//项目初始化参数
function get_param(urlArgs){
	var data={};
		$.ajax({
			type: "get",
			async :false,
			dataType:'json',
			data:urlArgs,
			url: base_url+"/BoxApi/Index/get_init_param",
			 success: function (respose) {
							//alert(JSON.stringify(respose));
				data=respose;
			 }
		})		
	return data;		
}


var after_init_function=[];
function after_init(f){
	after_init_function.push(f);
}
/*
 * Javascript base64_decode() base64解密函数
   用于解密base64加密的字符串
 * 吴先成  www.51-n.com ohcc@163.com QQ:229256237
 * @param string str base64加密字符串
 * @return string 解密后的字符串
*/
function base64_decode(str){
		var c1, c2, c3, c4;
		var base64DecodeChars = new Array(
				-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
				-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
				-1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57,
				58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0,  1,  2,  3,  4,  5,  6,
				7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
				25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
				37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
				-1, -1
		);
		var i=0, len = str.length, string = '';

		while (i < len){
				do{
						c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
				} while (
						i < len && c1 == -1
				);

				if (c1 == -1) break;

				do{
						c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
				} while (
						i < len && c2 == -1
				);

				if (c2 == -1) break;

				string += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

				do{
						c3 = str.charCodeAt(i++) & 0xff;
						if (c3 == 61)
								return string;

						c3 = base64DecodeChars[c3]
				} while (
						i < len && c3 == -1
				);

				if (c3 == -1) break;


				string += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

				do{
						c4 = str.charCodeAt(i++) & 0xff;
						if (c4 == 61) return string;
						c4 = base64DecodeChars[c4]
				} while (
						i < len && c4 == -1
				);

				if (c4 == -1) break;

				string += String.fromCharCode(((c3 & 0x03) << 6) | c4)
		}
		return string;
}